package cn.net.zhenchan.base.action;

import cn.net.zhenchan.base.BaseBO;
import cn.net.zhenchan.common.utils.EntityReflectionUtils;
import com.alibaba.fastjson.JSONObject;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

public class BaseClassAction<T extends BaseBO> extends BaseAction{

	public T bindingProperty(T t,String userId)
	{
//		t.setAddUserId(Integer.parseInt(userId));
//		t.setAddTime(StringUtil.returnDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
//		t.setEditTime(StringUtil.returnDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
//		t.setEditUserId(Integer.parseInt(userId));
//		t.setIsDelete("N");
		return t;
	}	
	public void doMethod(String url,String methodType)
	{
		HttpClient httpclient = new HttpClient();
		if("get".equals(methodType))
		{
			GetMethod get = new GetMethod(url);			
			get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
			try {
				httpclient.executeMethod(get);
			}catch(Exception e){
				logger.debug(e.getMessage());
			}	
		}else if("post".equals(methodType))
		{
			PostMethod post = new PostMethod(url);
			try {
				httpclient.executeMethod(post);
			}catch(Exception e){
				logger.debug(e.getMessage());
			}	
		}		
	}	
	public JSONObject ObjectChangJSONObject(Object o)
	{
		JSONObject json=new JSONObject();
		List<String> filedNameList= EntityReflectionUtils.getFiledNameList(o);
		if(filedNameList!=null && filedNameList.size()>0)
		{
			for(int i=0;i<filedNameList.size();i++)
			{
				Object rObject=EntityReflectionUtils.getFieldValue(o, filedNameList.get(i));
			    json.put(filedNameList.get(i),rObject);
			}
		}
		return json;		
	}		
	public void writeClient(HttpServletResponse response, String content, String type)
	{
		try{
			if("xml".equals(type))
			{
				if(content!=null && content.length()>0){
			    response.setContentType("text/xml;charset=UTF-8");} 
			}
			else
			{
				response.setContentType("text/html;charset=utf-8");
			}
			response.getWriter().write(content);
		}catch(Exception e){logger.error(e.getMessage(),e);}
	}

	public String exportExcelFile(HttpServletRequest request, HttpServletResponse response, List<Object> exportData)
	{
		try{
			String fileChName = request.getParameter("moduleName");
			String gridTitle = request.getParameter("gridTitle");
			String gridField = request.getParameter("gridField");
			String mergeField="";
			if(request.getParameter("mergeField")!=null)
			{
				mergeField=request.getParameter("mergeField");
			}			
			response.reset();
			response.setCharacterEncoding("ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; filename="+new String(fileChName.getBytes("GBK"), "ISO8859-1"));
			response.setHeader("Connection", "close");
			response.setHeader("Content-Type", "application/octet-stream");
			OutputStream os = response.getOutputStream();
	        String sheetTitle = "sheet1"; 			
			WritableWorkbook wbook = Workbook.createWorkbook(os);
	        WritableSheet wsheet = wbook.createSheet(sheetTitle, 0); 
			WritableFont wfont = new WritableFont(WritableFont.ARIAL, 14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);   
			WritableCellFormat wCellFormatTitle = new WritableCellFormat(wfont); 
			wCellFormatTitle.setBackground(Colour.YELLOW);			
			WritableFont wFontContent = new WritableFont(WritableFont.ARIAL, 12,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK); //建立excel字体  
			WritableCellFormat wCellFormatContent = new WritableCellFormat(wFontContent);
			if(gridTitle!=null && gridTitle.indexOf(",")>0)
			{				
				List<String> titleList=Arrays.asList(gridTitle.split(","));		
				for(int i=0;i<titleList.size();i++)
				{
					wsheet.setColumnView(i, 20);
					wsheet.addCell(new Label(i,0, titleList.get(i),wCellFormatTitle));
				}		
				List<String> propertieList=Arrays.asList(gridField.split(","));
				for(int i=0;i<propertieList.size();i++)
				{	
					for(int j=0;j<exportData.size();j++)
					{
						wsheet.setColumnView(i, 20);
						String value="";
						try{
							value=EntityReflectionUtils.getFieldValue(exportData.get(j), propertieList.get(i)).toString();
						}catch(Exception e)
						{	
							value="";
						}
						wsheet.addCell(new Label(i,j+1,value,wCellFormatContent));
					}
				}				
				if(mergeField!=null && mergeField.length()>0 && mergeField.indexOf(",")>0)
				{
					List<String> mergeList=Arrays.asList(mergeField.split(","));	
					Map<String,Map<String,List<String>>> propertieKeyValueKeyCoordinate=getPropertieMapCoordinate(propertieList,exportData,mergeList);
					Map<String,List<String>> propertieMapValueSet=propertieKeyValueKeyCoordinate.get(mergeList.get(0));				
					List<String> keyValueSet=Arrays.asList(propertieMapValueSet.keySet().toArray().toString());
					for(int j=0;j<keyValueSet.size();j++)
					{
						List<String> coordinateList=propertieMapValueSet.get(keyValueSet.get(j));
						if(coordinateList.size()>1)
						{
						   wsheet.mergeCells(Integer.parseInt(coordinateList.get(0).split(",")[0]),Integer.parseInt(coordinateList.get(0).split(",")[1]),Integer.parseInt(coordinateList.get(coordinateList.size()-1).split(",")[0]),Integer.parseInt(coordinateList.get(coordinateList.size()-1).split(",")[1]));
						   for(int i=1;i<mergeList.size();i++)
						   {
							   wsheet.mergeCells(propertieList.indexOf(mergeList.get(i)),Integer.parseInt(coordinateList.get(0).split(",")[1]),propertieList.indexOf(mergeList.get(i)),Integer.parseInt(coordinateList.get(coordinateList.size()-1).split(",")[1]));
						   }					   
						}					
					}
				}
			}			       
			wbook.write(); 
			wbook.close(); 
			os.flush();
			os.close(); 
		}catch(Exception e){
		}	
		return "ok";
	}
	
	private Map<String,Map<String,List<String>>> getPropertieMapCoordinate(List<String> propertieList,List exportData,List<String> mergeList)
	{
		Map<String,Map<String,List<String>>> propertieKeyValueKeyCoordinate=new HashMap<String,Map<String,List<String>>>();		
		Map<String,Set<String>> propertieMapValueSet=getPropertieMapValueSet(propertieList,exportData,mergeList);
		
		for(int i=0;i<propertieList.size();i++)
		{
			if(mergeList.get(0).equals(propertieList.get(i)))
			{
				Set<String> difPropertieUnderValue=propertieMapValueSet.get(propertieList.get(i));
				Iterator iteratorPropertieUnderValue=difPropertieUnderValue.iterator();	
				Map<String,List<String>> valueKeyCoordinateList=new HashMap<String,List<String>>();			
				while(iteratorPropertieUnderValue.hasNext())
				{
					String groupFirstValue=iteratorPropertieUnderValue.next().toString();		
					List<String> xyList=new ArrayList<String>();
					for(int j=0;j<exportData.size();j++)
					{
						String value="";
						try{
							value=EntityReflectionUtils.getFieldValue(exportData.get(j), propertieList.get(i)).toString();
						}catch(Exception e)
						{	
							value="error";
						}
						if(groupFirstValue.equals(value))
						{
							xyList.add(i+","+(j+1));
						}
					}
					valueKeyCoordinateList.put(groupFirstValue, xyList);
				}
				propertieKeyValueKeyCoordinate.put(propertieList.get(i), valueKeyCoordinateList);	
			}
		}		
		return propertieKeyValueKeyCoordinate;
	}
	private Map<String,Set<String>> getPropertieMapValueSet(List<String> propertieList,List exportData,List<String> mergeList)
	{
		Map<String,Set<String>> propertieMapValueSet=new HashMap<String,Set<String>>();		
		for(int i=0;i<propertieList.size();i++)
		{
			if(mergeList.get(0).equals(propertieList.get(i)))
			{
				Set<String> setValue=new HashSet<String>();
				for(int j=0;j<exportData.size();j++)
				{
					String value="";
					try{
						value=EntityReflectionUtils.getFieldValue(exportData.get(j), propertieList.get(i)).toString();
					}catch(Exception e)
					{	
						value="error";
					}
					setValue.add(value);
				}
				propertieMapValueSet.put(propertieList.get(i), setValue);
			}
		}		
		return propertieMapValueSet;
	}
}
